package wykop.download;

import java.net.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;

public class WeightedProxyList {

	Map<Proxy, Integer> positions = Maps.newHashMap();
	Proxy[] proxys;
	Integer[] successes;

	public WeightedProxyList(final List<Proxy> proxyList) {
		super();
		proxys = new Proxy[proxyList.size()];
		successes = new Integer[proxyList.size()];

		for (int i = 0; i < proxyList.size(); i++) {
			proxys[i] = proxyList.get(i);
			successes[i] = 0;
			positions.put(proxys[i], i);
		}
	}

	public Proxy head() {
		return proxys[0];
	}

	public synchronized void increment(final Proxy proxy) {
		int position = positions.get(proxy);
		successes[position] += 1;

		while (position > 0 && successes[position] < successes[position - 1]) {

			final Proxy temp = proxys[position - 1];

			System.out.println("Swap " + proxy + " and " + temp);

			positions.put(temp, position);
			positions.put(proxy, position - 1);

			proxys[position] = temp;
			proxys[position - 1] = proxy;
			position = position - 1;
		}

	}

	public synchronized Iterable<Proxy> proxyList() {
		return Arrays.asList(Arrays.copyOf(proxys, proxys.length));
	}

}